#include <PubSubClient.h>
#include "auto_wifi.h"
#include "mqtt.h"

WiFiClient client;
PubSubClient mqttClient(client);

String mqttClient_id;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];

// 传感器使用的针脚
const int sensorPin = D2;
int sensorValue = 0;
short int sensorCount = 0;

unsigned long lastMillis = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(100);
  pinMode(sensorPin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  //启动配网
  wifi_setup();
  initMQTT();
  connectMQTT();
}

void loop() {
  mqttClient.loop();
  sensorValue = digitalRead(sensorPin);
  unsigned long currentMillis = millis();
  if (sensorValue == 1) {
    sensorCount ++;
  } else {
    sensorCount = 0;
  }
  // 必须有持续的运动才会被视为有效物体移动，为了过滤杂音
  if (sensorCount >= 1000) {
    sensorCount = 0;
    // 和上次拍照间隔时间超过5s
    if ((currentMillis - lastMillis) >= 5000) {
      // 延迟是为了能正确的拍到物体，防止拍照太早
      delay(300);
      mqttClient.publish(pubTopic, "1");
      lastMillis = millis();
    }
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
  }
  digitalWrite(LED_BUILTIN, HIGH);

  Serial.println(sensorCount);
}

void initMQTT() {
  //init mqtt broker
  mqttClient.setServer(mqtt_broker, mqtt_port);
  mqttClient.setCallback(callback);
  mqttClient_id = "esp8266-client-";
  mqttClient_id += String(WiFi.macAddress());
}

void connectMQTT() {
  Serial.println("正在连接MQTT服务...");
  int mqttRetryCount = 0;
  while (!mqttClient.connect(mqttClient_id.c_str(), mqtt_username, mqtt_password)) {
    mqttRetryCount ++;
    if (mqttRetryCount > MQTT_RETRY_COUNT) {
      delay(1000);
      ESP.restart();
      return;
    }
    Serial.println("连接MQTT失败，重试" + (String)mqttRetryCount);
  }
  Serial.printf("连接MQTT成功！ %s", mqttClient_id.c_str());
  Serial.println();
  // 订阅 & 发布
  // mqttClient.subscribe(subTopic);
}

void callback(char *topic, byte *payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  String msg;
  for (int i = 0; i < length; i++) {
    msg = msg + (char) payload[i];
  }
  Serial.println(msg);
}
